<?php

namespace admin\controllers;

use Yii;
use admin\models\User;
use admin\models\Order;
use admin\models\Product;
use admin\models\AdminUser;
use admin\models\UserCoupon;
use admin\models\UserCharge;
use admin\models\UserRebate;
use admin\models\UserWithdraw;
use admin\models\UserGive;
use admin\models\Retail;
use common\helpers\Hui;
use common\helpers\Html;

class UserController extends \admin\components\Controller
{
    /**
     * @authname 会员列表
     */
    public function actionList()
    {
        $query = (new User)->listQuery();

        $html = $query->getTable([
            ['type' => 'checkbox'],
            'id',
            'nickname' => ['type' => 'text'],
            'mobile',
            // 'pid' => ['header' => '推荐人', 'value' => function ($row) {
            //     return $row->getParentLink();
            // }],
            'pid' => ['header' => '推荐人ID'],
            'adminUser.username' => ['header' => '代理商账号'],
            'account',
            ['header' => '总盈亏', 'value' => function($row) {
                return $row->profit_account + $row->loss_account;
            }],
            ['header' => '手续费', 'value' => function($row) {
                return  Order::find()->where(['user_id' => $row->id])->select('SUM(fee) fee')->one()->fee;
            }],
            // 'profit_account',
            // 'loss_account',
            'created_at',
            'login_time',
            'type' => u()->power < AdminUser::POWER_ADMIN?['search' => 'select']:['search' => 'select', 'type' => 'select'],
            'state' => ['search' => 'select'],
            ['header' => '操作', 'width' => '120px', 'value' => function ($row) {
                if ($row['state'] == User::STATE_VALID) {
                    $deleteBtn = Hui::dangerBtn('冻结', ['deleteUser', 'id' => $row->id], ['class' => 'deleteBtn']);
                } else {
                    $deleteBtn = Hui::successBtn('恢复', ['deleteUser', 'id' => $row->id], ['class' => 'deleteBtn']);
                }
                return implode(str_repeat('&nbsp;', 2), [
                    Hui::primaryBtn('修改密码', ['editUserPass', 'id' => $row->id], ['class' => 'editBtn']),
                    $deleteBtn
                ]);
            }]
        ], [
            'searchColumns' => [
                'id',
                'nickname',
                'mobile',
                'adminUser.username' => ['header' => '代理商账号'],
                'pid' => ['header' => '推荐人ID'],
                'start_time' => ['type' => 'datepicker']
            ]
        ]);

        // 会员总数，总手数，总余额
        $count = User::find()->where(['type' => User::TYPE_USER])->count();
        $hand = Order::find()->joinWith(['user'])->where(['user.type' => User::TYPE_USER])->select('SUM(hand) hand')->one()->hand ?: 0;
        $amount = User::find()->where(['type' => User::TYPE_USER])->select('SUM(account) account')->one()->account ?: 0;

        return $this->render('list', compact('html', 'count', 'hand', 'amount'));
    }

    /**
     * @authname 修改会员密码
     */
    public function actionEditUserPass() 
    {
        $user = User::findModel(get('id'));
        $user->password = post('password');
        if ($user->validate()) {
            $user->hashPassword()->update(false);
            return success();
        } else {
            return error($user);
        }
    }

    /**
     * @authname 冻结/恢复用户
     */
    public function actionDeleteUser() 
    {
        $user = User::find()->where(['id' => get('id')])->one();

        if ($user->toggle('state')) {
            return success('冻结成功！');
        } else {
            return success('账号恢复成功！');
        }
    }

    /**
     * @authname 赠送优惠券
     */
    public function actionSendCoupon()
    {
        $ids = post('ids');

        // 送给所有人
        if (!$ids) {
            $ids = User::find()->map('id', 'id');
        }
        UserCoupon::sendCoupon($ids, post('coupon_id'), post('number') ?: 1);
        return success('赠送成功');
    }

    /**
     * @authname 会员持仓列表
     */
    public function actionPositionList()
    {
        $query = (new User)->listQuery()->andWhere(['user.state' => User::STATE_VALID]);

        $order = [];
        $html = $query->getTable([
            'id',
            'nickname' => ['type' => 'text'],
            'mobile',
            'type' => ['search' => 'select'],
            ['header' => '盈亏', 'value' => function ($row) use (&$order) {
                $order = Order::find()->where(['user_id' => $row['id'], 'order_state' => Order::ORDER_POSITION])->select(['SUM(hand) hand', 'SUM(profit) profit'])->one();
                if ($order->profit == null) {
                    return '无持仓';
                } elseif ($order->profit >= 0) {
                    return Html::redSpan($order->profit);
                } else {
                    return Html::greenSpan($order->profit);
                }
            }],
            ['header' => '持仓手数', 'value' => function ($row) use (&$order) {
                if ($order->hand == null) {
                    return '无持仓';
                } else {
                    return $order->hand;
                }
            }],
            'account',
            'state'
        ], [
            'searchColumns' => [
                'nickname',
                'mobile',
                'created_at' => ['type' => 'date']
            ]
        ]);

        return $this->render('positionList', compact('html'));
    }

    /**
     * @authname 会员赠金记录
     */
    public function actionGiveAmount()
    {
        $query = (new UserGive)->listQuery()->manager();
        $html = $query->getTable([
            'id',
            'user.username',
            'user.nickname',
            'amount',
            'created_at'
        ], [
            'searchColumns' => [
                'user.username',
                'created_at' => ['type' => 'date']
            ]    
        ]);
        $amount = UserGive::find()->manager()->select('SUM(amount) amount')->one()->amount ?: 0;
        return $this->render('giveAmount', compact('html', 'amount'));
    }

    /**
     * @authname 会员赠金
     */
    public function actionGiveList()
    {
        if (req()->isPost) {
            $userGive = new UserGive;
            $userGive->user_id = get('id');
            $userGive->amount = post('amount');
            if($userGive->insert(false)) {
                $user = User::findModel(get('id'));
                $user->account += post('amount');
                if ($user->update()) {
                    return success();
                } else {
                    return error($user);
                }
            }
        }

        $query = (new User)->listQuery()->andWhere(['user.state' => User::STATE_VALID]);

        $html = $query->getTable([
            'id',
            'nickname',
            'mobile',
            'account',
            'type' => ['search' => 'select'],
            ['header' => '操作', 'width' => '40px', 'value' => function ($row) {
                return Hui::primaryBtn('赠金', ['', 'id' => $row['id']], ['class' => 'giveBtn']);
            }]
        ], [
            'searchColumns' => [
                'nickname',
                'mobile'
            ]
        ]);

        return $this->render('giveList', compact('html'));
    }

    /**
     * @authname 会员出金管理
     */
    public function actionWithdrawList()
    {
        $query = (new UserWithdraw)->listQuery()->joinWith(['user.parent'])->andWhere(['user.state' => User::STATE_VALID])->orderBy('op_state');
        $countQuery = (new UserWithdraw)->listQuery()->joinWith(['user'])->andWhere(['user.state' => User::STATE_VALID])->andWhere(['op_state' => UserWithdraw::OP_STATE_PASS]);
        $count = $countQuery->select('SUM(amount) amount')->one()->amount ?: 0;

        $html = $query->getTable([
            'user.id',
            'user.nickname',
            'user.mobile',
            'user.account',
            'out_sn',
            'amount' => '出金金额',
            'updated_at',
            'op_state' => ['search' => 'select'],
            ['header' => '操作', 'width' => '70px', 'value' => function ($row) {
                $state =  Hui::primaryBtn('更改出金状态', ['user/stateWithdraw', 'id' => $row['id']], ['class' => 'layer.iframe']);

                if ($row['op_state'] == UserWithdraw::OP_STATE_WAIT) {
                    return Hui::primaryBtn('会员出金', ['user/verifyWithdraw', 'id' => $row['id']], ['class' => 'layer.iframe']) . $state;
                } else {
                    return Html::successSpan('已审核');
                }
            }]
        ], [
            'searchColumns' => [
                'out_sn',
                'user.nickname',
                'user.pid' => ['header' => '推荐人ID'],
                'user.admin_id' => ['header' => '代理商ID'],
                'user.mobile',
                'time' => ['header' => '审核时间', 'type' => 'dateRange']
            ],
            'ajaxReturn' => [
                'count' => $count
            ]
        ]);
        

        return $this->render('withdrawList', compact('html', 'count'));
    }

    /**
     * @authname 更改出金状态
     */
    public function actionStateWithdraw($id)
    {
        $model = UserWithdraw::find()->where(['id' => $id])->one();

        if (req()->isPost) {
            $model->op_state = post('UserWithdraw')['op_state'];
            if($model->update()) {
                return success();
            }else {
                return error($model);
            }
        }

        return $this->render('stateWithdraw', compact('model'));
    }

    /**
     * @authname 会员出金操作
     */
    public function actionVerifyWithdraw($id)
    {
        $model = UserWithdraw::find()->with('user.userAccount')->where(['id' => $id])->one();

        if (req()->isPost) {
            $model->op_state = post('state');
            // if ($model->op_state == UserWithdraw::OP_STATE_PASS) {
            //     $info = $model->newoutUserMoney();
                
            //     if ($info['resp_code'] != '000000') {
            //         return error($info['resp_msg']);
            //     }
            // }
            if ($model->update()) {
                if ($model->op_state == UserWithdraw::OP_STATE_DENY) {
                    $model->user->account += $model->amount;
                    $model->user->update();    
                }
                return success();
            } else {
                return error($model);
            }
        }

        return $this->render('verifyWithdraw', compact('model'));
    }

    /**
     * @authname 会员充值记录
     */
    public function actionChargeRecordList()
    {
        $query = (new UserCharge)->listQuery()->joinWith(['user.parent'])->orderBy('userCharge.id DESC');
        $countQuery = (new UserCharge)->listQuery()->joinWith(['user']);
        $count = $countQuery->select('SUM(amount) amount')->one()->amount ?: 0;

        $html = $query->getTable([
            'user.id',
            'user.nickname' => '充值人',
            'user.mobile',
            'user.pid' => ['header' => '推荐人id'],
            'amount',
            ['header' => '推荐人', 'value' => function ($row) {
                return $row->user->getParentLink('user.id');
            }],
            'user.account',
            'charge_type',
            'created_at'
        ], [
            'searchColumns' => [
                'user.id',
                'user.nickname',
                'user.pid' => ['header' => '推荐人id'],
                'user.admin_id' => ['header' => '代理商id'],
                'user.mobile',
                'time' => ['header' => '充值时间', 'type' => 'dateRange'],
            ],
            'ajaxReturn' => [
                'count' => $count
            ]
        ]);

        return $this->render('chargeRecordList', compact('html', 'count'));
    }

    /**
     * @authname 审核经纪人
     */
    public function actionVerifyManager()
    {
        if (req()->isPost) {
            $model = User::find()->with('userExtend')->where(['id' => get('id')])->one();
            $model->apply_state = get('apply_state');
            if ($model->apply_state == User::APPLY_STATE_PASS) {
                $model->is_manager = User::IS_MANAGER_YES;
                $retail = Retail::find()->where(['code' => $model->userExtend->coding])->one();
                $model->admin_id = $retail->admin_id;
            }
            if ($model->update()) {
                return success();
            } else {
                return error($model);
            }
        }

        $query = (new User)->listQuery()->joinWith(['userAccount'])->andWhere(['user.apply_state' => User::APPLY_STATE_WAIT, 'user.state' => User::STATE_VALID]);

        $html = $query->getTable([
            'id',
            'nickname',
            'mobile',
            // 'pid' => ['header' => '推荐人', 'value' => function ($row) {
            //     return $row->getParentLink();
            // }],
            // 'userAccount.realname',
            // 'userAccount.id_card',
            // 'userAccount.bank_name',
            // 'userAccount.bank_card',
            // 'userAccount.bank_user',
            // 'userAccount.bank_mobile',
            // 'userAccount.bank_address',
            // 'userAccount.address',
            'created_at',
            ['type' => [], 'value' => function ($row) {
                return implode(str_repeat('&nbsp;', 2), [
                    Hui::primaryBtn('审核通过', ['', 'id' => $row->id, 'apply_state' => User::APPLY_STATE_PASS], ['class' => 'verifyBtn']),
                    Hui::dangerBtn('不通过', ['', 'id' => $row->id, 'apply_state' => User::APPLY_STATE_DENY], ['class' => 'verifyBtn'])
                ]);
            }]
        ], [
            'searchColumns' => [
                'id',
                'nickname',
                'mobile'
            ]
        ]);

        return $this->render('verifyManager', compact('html'));
    }

    /**
     * @authname 返点记录列表
     */
    public function actionRebateList()
    {
        $query = (new UserRebate)->listQuery()->manager()->andWhere('userRebate.pid > ' . AdminUser::POWER_SUPER);
        $count = $query->sum('amount') ?: 0;

        $html = $query->getTable([
            'id' => '返点编号',
            'user.nickname' => ['header' => '会员昵称（手机号）', 'value' => function ($row) {
                return Html::a($row->user->nickname . "({$row->user->mobile})", ['', 'search[user.id]' => $row->user->id], ['class' => 'parentLink']);
            }],
            'parent.nickname' => ['header' => '经纪人昵称（手机号）', 'value' => function ($row) {
                return $row->user->getParentLink();
            }],
            'amount',
            'point' => function ($row) {
                return $row->point . '%';
            },
            'created_at' => '返点时间'
        ], [
            'searchColumns' => [
                'user.id' => ['header' => '会员ID'],
                'user.nickname' => ['header' => '会员昵称'],
                'user.mobile' => ['header' => '会员手机'],
                'parent.mobile' => ['header' => '经纪人手机号'],
                'time' => 'timeRange'
            ],
            'ajaxReturn' => [
                'count' => $count
            ]
        ]);

        return $this->render('rebateList', compact('html', 'count'));
    }
}
